<template>
  <div class="bom-container">
    <!-- 搜索区域 -->
    <div class="search-area">
      <el-input 
        v-model="searchForm.bomCode" 
        placeholder="BOM编号" 
        clearable 
        class="search-input" 
        @keyup.enter="handleSearch"
        @clear="handleSearch"
      />
      <el-input 
        v-model="searchForm.materialCode" 
        placeholder="物料编号" 
        clearable 
        class="search-input"
        @keyup.enter="handleSearch"
        @clear="handleSearch"
      />
      <el-button type="primary" @click="handleSearch" color="#409EFF">
        <el-icon><Search /></el-icon>
        搜索
      </el-button>
      <el-button @click="handleResetSearch" class="reset-button">
        重置
      </el-button>
    </div>

    <!-- 操作按钮区域 -->
    <div class="operation-area">
      <el-button type="primary" @click="handleAdd" color="#409EFF" class="add-button">
        + 添加
      </el-button>
      <el-button @click="handleBatchDelete" class="batch-delete-button">批量删除</el-button>
    </div>

    <!-- 表格区域 -->
    <el-table
      :data="tableData"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="bomCode" label="bom编号" />
      <el-table-column prop="materialCode" label="物料编号" />
      <el-table-column prop="materialName" label="物料名称" />
      <el-table-column prop="supplier" label="供应商" />
      <el-table-column prop="version" label="版本" />
      <el-table-column prop="remark" label="备注" />
      <el-table-column prop="state" label="状态">
        <template #default="scope">
          <el-tag
            :type="getStatusType(scope.row.state)"
            class="status-tag"
          >
            {{ scope.row.state }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button
            class="edit-button"
            size="small"
            @click="handleEdit(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            class="delete-button"
            size="small"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :small="false"
        :disabled="false"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="800px"
      :close-on-click-modal="false"
      class="bom-dialog custom-dialog"
      :show-close="true"
      destroy-on-close
      top="5vh"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="120px"
        class="bom-form"
      >
        <el-form-item 
          label="BOM编码" 
          prop="bomCode"
          required
        >
          <el-input 
            v-model="formData.bomCode" 
            placeholder="请输入BOM编码"
            clearable
            :disabled="true"
          />
        </el-form-item>

        <el-form-item 
          label="物料编码" 
          prop="materialCode"
          required
          class="material-code-item"
        >
          <div class="material-code-wrapper">
            <el-input 
              v-model="formData.materialCode" 
              placeholder="请输入物料编码"
              readonly
              class="material-input"
            />
            <el-button type="primary" @click="handleSearchMaterial" class="search-button">
              <el-icon><Search /></el-icon>
            </el-button>
          </div>
        </el-form-item>

        <el-form-item 
          label="物料名称" 
          prop="materialName"
          required
        >
          <el-input 
            v-model="formData.materialName" 
            placeholder="请输入物料名称"
            clearable
          />
        </el-form-item>

        <el-form-item 
          label="供应商" 
          prop="supplier"
          required
        >
          <el-input 
            v-model="formData.supplier" 
            placeholder="请输入供应商"
            clearable
          />
        </el-form-item>

        <el-form-item 
          label="版本号" 
          prop="version"
          required
          class="version-item"
        >
          <el-input-number
            v-model="formData.version"
            :min="1"
            controls-position="right"
            placeholder="请输入版本号"
            class="custom-input-number"
          />
        </el-form-item>

        <el-form-item 
          label="状态" 
          prop="state"
          required
        >
          <el-radio-group v-model="formData.state">
            <el-radio label="正常">正常</el-radio>
            <el-radio label="已删除">已删除</el-radio>
            <el-radio label="已禁用">已禁用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="备注说明" prop="remark">
          <el-input
            v-model="formData.remark"
            type="textarea"
            :rows="4"
            placeholder="请输入备注说明"
            resize="none"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false" class="cancel-button">取消</el-button>
          <el-button type="primary" @click="handleSubmit" class="confirm-button">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 物料搜索弹窗 -->
    <el-dialog
      v-model="materialDialogVisible"
      title="信息"
      width="1200px"
      :close-on-click-modal="false"
      class="material-dialog custom-dialog"
      destroy-on-close
      append-to-body
      top="8vh"
    >
      <div class="search-header">
        <div class="search-inputs">
          <el-input
            v-model="materialSearchForm.code"
            placeholder="物料编码"
            clearable
            class="search-input"
          />
          <el-input
            v-model="materialSearchForm.batch"
            placeholder="物料批次"
            clearable
            class="search-input"
          />
          <el-button type="primary" class="search-btn" @click="handleMaterialSearch">
            <el-icon><Search /></el-icon>
          </el-button>
        </div>
      </div>

      <el-table
        :data="GetMaterialPickingData"
        style="width: 100%"
        @selection-change="handleMaterialSelectionChange"
        height="400"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column prop="materialCode" label="物料编码" min-width="120" />
        <el-table-column prop="batch" label="批次" min-width="80" />
        <el-table-column prop="number" label="数量" min-width="80" />
        <el-table-column prop="materialUnit" label="单位" min-width="80" />
        <el-table-column prop="picker" label="拣货人" min-width="100" />
        <el-table-column prop="outboundWarehouse" label="出库仓" min-width="100" />
        <el-table-column prop="storagewarehouse" label="存储仓" min-width="100" />
        <el-table-column prop="updateTime" label="更新时间" min-width="160">
          <template #default="scope">
            {{ formatDate(scope.row.updateTime) }}
          </template>
        </el-table-column>
      </el-table>

      <!-- 使用Element Plus的分页组件替换自定义分页 -->
      <div class="material-pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50]"
          :small="true"
          :background="true"
          layout="total, sizes, prev, pager, next"
          :total="totalItems"
        />
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="materialDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleMaterialConfirm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, watch } from 'vue'
import { Search, ArrowLeft } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import http from '@/api/http'

// 搜索表单数据
const searchForm = ref({
  bomCode: '',
  materialCode: ''
})

// 表格数据
const tableData = ref([])

// 选中的行数据
const selectedRows = ref([])

// 分页数据
const pagination = reactive({
  currentPage: 1,    // 当前页
  pageSize: 10,      // 每页显示条数
  total: 0           // 总条数
})

// 处理表格选择变化
const handleSelectionChange = (val) => {
  selectedRows.value = val
}

// 处理搜索
const handleSearch = () => {
  pagination.currentPage = 1 // 搜索时重置到第一页
  getBom()
}

// 处理重置搜索
const handleResetSearch = () => {
  searchForm.value.bomCode = ''
  searchForm.value.materialCode = ''
  pagination.currentPage = 1 // 重置到第一页
  getBom() // 重置后重新查询
}

// 处理页码变化
const handleCurrentChange = (page) => {
  pagination.currentPage = page
  getBom()
}

// 处理每页显示条数变化
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1 // 重置到第一页
  getBom()
}



// 弹窗相关
const dialogVisible = ref(false)
const dialogTitle = ref('添加')
const formRef = ref(null)
const isEdit = ref(false) // 标识是否为编辑模式
const editId = ref(0) // 编辑时的记录ID

// 表单数据
const formData = reactive({
  bomCode: '',
  materialCode: '',
  materialName: '',
  supplier: '',
  version: 1,
  state: '正常',
  remark: ''
})

// 表单校验规则
const rules = {
  bomCode: [{ required: true, message: '请输入BOM编码', trigger: 'blur' }],
  materialCode: [{ required: true, message: '请输入物料编码', trigger: 'blur' }],
  materialName: [{ required: true, message: '请输入物料名称', trigger: 'blur' }],
  supplier: [{ required: true, message: '请输入供应商', trigger: 'blur' }],
  version: [{ required: true, message: '请输入版本号', trigger: 'blur' }],
  state: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

// 处理添加按钮点击
const handleAdd = () => {
  dialogTitle.value = '添加'
  isEdit.value = false
  editId.value = 0
  dialogVisible.value = true
  // 重置表单
  resetForm()
  // 获取新的BOM编码
  GetBomCode()
}

// 处理批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的记录')
    return
  }
  
  ElMessageBox.confirm('确认删除选中的记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const ids = selectedRows.value.map(row => row.id)
    if (ids.length > 0) {
      DeleteBom(ids)
    } else {
      ElMessage.warning('所选记录无效')
    }
  })
}



// 处理编辑
const handleEdit = (row) => {
  dialogTitle.value = '编辑'
  isEdit.value = true
  editId.value = row.id
  
  // 回显数据到表单
  formData.bomCode = row.bomCode || ''
  formData.materialCode = row.materialCode || ''
  formData.materialName = row.materialName || ''
  formData.supplier = row.supplier || ''
  formData.version = row.version || 1
  formData.state = row.state || '正常'
  formData.remark = row.remark || ''
  
  dialogVisible.value = true
}

// 处理删除
const handleDelete = (row) => {
  if (!row.id) {
    ElMessage.warning('无效的记录')
    return
  }
  ElMessageBox.confirm('确认删除该记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    DeleteBom([row.id])
  })
}

// 获取状态标签类型
const getStatusType = (state) => {
  const statusMap = {
    '正常': 'success',
    '禁用': 'danger',
    '删除': 'info'
  }
  return statusMap[state] || 'info'
}

// 物料搜索相关
const materialDialogVisible = ref(false)
const materialSearchForm = reactive({
  code: '',
  batch: ''
})
const currentPage = ref(1)
const pageSize = ref(10)
const totalItems = ref(4)
const selectedMaterial = ref(null)

// 处理物料搜索按钮点击
const handleSearchMaterial = () => {
  materialDialogVisible.value = true
}

// 处理物料搜索
const handleMaterialSearch = () => {
  // TODO: 实现搜索功能
  GetMaterialPicking()
}

// 处理物料选择
const handleMaterialSelectionChange = (selection) => {
  if (selection.length > 0) {
    selectedMaterial.value = selection[0]
  } else {
    selectedMaterial.value = null
  }
}

// 处理物料确认
const handleMaterialConfirm = () => {
  if (selectedMaterial.value) {
    formData.materialCode = selectedMaterial.value.materialCode
    formData.materialName = selectedMaterial.value.materialDesc
    materialDialogVisible.value = false
  } else {
    ElMessage.warning('请选择物料')
  }
}

// 处理表单提交
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    if (isEdit.value) {
      // 编辑模式：将表单数据映射到UpdateBomAsyncData
      UpdateBomAsyncData.id = editId.value
      UpdateBomAsyncData.bomCode = formData.bomCode
      UpdateBomAsyncData.materialCode = formData.materialCode
      UpdateBomAsyncData.materialName = formData.materialName
      UpdateBomAsyncData.supplier = formData.supplier
      UpdateBomAsyncData.version = formData.version
      UpdateBomAsyncData.state = formData.state
      UpdateBomAsyncData.remark = formData.remark

      // 调用更新接口
      await UpdateBomAsync()
    } else {
      // 添加模式：将表单数据映射到AddBomData
      AddBomData.id = 0
      AddBomData.bomCode = formData.bomCode
      AddBomData.materialCode = formData.materialCode
      AddBomData.materialName = formData.materialName
      AddBomData.supplier = formData.supplier
      AddBomData.version = formData.version
      AddBomData.state = formData.state
      AddBomData.remark = formData.remark

      // 调用添加接口
      await AddBom()
    }
    
    dialogVisible.value = false
  } catch (error) {
    console.error('表单验证失败', error)
  }
}

onMounted(()=>{
    GetMaterialPicking()
    getBom();
})

//----------获取物料下拉框
const GetMaterialPickingData =ref([])
const GetMaterialPicking =()=>{
    http.get('api/Bom/GetMaterialPicking').then(res=>{
        GetMaterialPickingData.value = res.data
    })
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  return dateString.replace('T', ' ').split('.')[0]
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  // 手动重置formData到初始状态
  Object.assign(formData, {
    bomCode: '',
    materialCode: '',
    materialName: '',
    supplier: '',
    version: 1,
    state: '正常',
    remark: ''
  })
}

const AddBomData=reactive({
    "id": 0,
  "bomCode": "",
  "materialCode": "",
  "materialName": "",
  "supplier": "",
  "version": 0,
  "state": "",
  "remark": ""
})

const AddBom = () => {
    return http.post('api/Bom/AddBom', AddBomData).then(res => {
       res.status == true ? ElMessage.success('添加成功') : ElMessage.error('添加失败')
       getBom()
    })
}

const getBomData=ref([])
const getBom = () => {
    // 构建查询参数
    const params = new URLSearchParams()
    
    // 添加分页参数
    params.append('pageIndex', pagination.currentPage.toString())
    params.append('pageSize', pagination.pageSize.toString())
    
    // 如果有BOM编码条件，添加到查询参数
    if (searchForm.value.bomCode && searchForm.value.bomCode.trim()) {
        params.append('bomCode', searchForm.value.bomCode.trim())
    }
    
    // 如果有物料编码条件，添加到查询参数
    if (searchForm.value.materialCode && searchForm.value.materialCode.trim()) {
        params.append('materialCode', searchForm.value.materialCode.trim())
    }
    
    // 构建最终的URL
    const url = `api/Bom/GetBom?${params.toString()}`
    
    http.get(url).then(res => {
        if (res && res.data) {
            getBomData.value = res.data.rows || res.data // 兼容不同的响应格式
            pagination.total = res.data.total || res.data.length || 0 // 设置总条数
        } else {
            getBomData.value = []
            pagination.total = 0
        }
    }).catch(error => {
        console.error('查询BOM数据失败:', error)
        ElMessage.error('查询数据失败')
        getBomData.value = []
        pagination.total = 0
    })
}

// 监听getBomData的变化，更新tableData
watch(getBomData, (newVal) => {
  tableData.value = newVal
}, { immediate: true })

//批量删除
const DeleteBom=(ids)=>{
    const params = new URLSearchParams()
    params.append('id', ids.join(','))
    
    http.post('api/Bom/DeleteBom?' + params.toString()).then(res=>{
        if(res.status) {
            ElMessage.success('删除成功')
            // 删除后检查当前页是否还有数据，如果没有则回到上一页
            const remainingItems = pagination.total - ids.length
            const maxPage = Math.ceil(remainingItems / pagination.pageSize)
            if (pagination.currentPage > maxPage && maxPage > 0) {
                pagination.currentPage = maxPage
            }
            getBom() // 刷新列表
        } else {
            ElMessage.error('删除失败')
        }
    }).catch(() => {
        ElMessage.error('删除请求失败')
    })
}

//获取一个雪花id用于生成bom编码
const GetBomCode = () => {
    return http.get('api/Bom/GetBomCode').then(res => {
        formData.bomCode = res.toString();
    })
}

const UpdateBomAsyncData=reactive({
  "id": 0,
  "bomCode": "",
  "materialCode": "",
  "materialName": "",
  "supplier": "",
  "version": 0,
  "state": "",
  "remark": ""
})

const UpdateBomAsync = () => {
    return http.post('api/Bom/UpdateBom', UpdateBomAsyncData).then(res => {
        res.status == true ? ElMessage.success('更新成功') : ElMessage.error('更新失败')
        getBom()
    })
}



</script>

<style scoped>
.bom-container {
  padding: 20px;
}

.search-area {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
  align-items: center;
}

.search-input {
  width: 200px;
}

.operation-area {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
  align-items: center;
}

.add-button {
  background-color: #409EFF;
  border-color: #409EFF;
}

.batch-delete-button {
  background-color: #FFA2A2;
  border-color: #FFA2A2;
  color: white;
}



.reset-button {
  color: #606266;
  border-color: #dcdfe6;
  background-color: #ffffff;
}

.reset-button:hover {
  color: #409EFF;
  border-color: #c6e2ff;
  background-color: #ecf5ff;
}

.edit-button {
  background-color: #409EFF;
  border-color: #409EFF;
  color: white;
}

.delete-button {
  background-color: #FFA2A2;
  border-color: #FFA2A2;
  color: white;
}

:deep(.el-table) {
  margin-top: 20px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
  padding: 20px 0;
}

:deep(.el-pagination) {
  .el-pagination__total {
    color: #606266;
    font-weight: 400;
  }
  
  .el-pagination__sizes {
    .el-select .el-input {
      width: 110px;
    }
  }
  
  .btn-prev, .btn-next {
    background-color: #f4f4f5;
    color: #606266;
    border: 1px solid #dcdfe6;
  }
  
  .btn-prev:hover, .btn-next:hover {
    color: #409EFF;
  }
  
  .el-pager li {
    background-color: #f4f4f5;
    color: #606266;
    border: 1px solid #dcdfe6;
    margin: 0 2px;
  }
  
  .el-pager li:hover {
    color: #409EFF;
  }
  
  .el-pager li.is-active {
    background-color: #409EFF;
    color: #fff;
    border-color: #409EFF;
  }
}

:deep(.status-tag) {
  border: none;
  padding: 2px 10px;
}

:deep(.status-tag.el-tag--success) {
  background-color: #E1F3D8;
  color: #67C23A;
}

:deep(.status-tag.el-tag--danger) {
  background-color: #FFE7E7;
  color: #FF0000;
}

:deep(.status-tag.el-tag--info) {
  background-color: #F4F4F5;
  color: #909399;
}

.bom-dialog {
  :deep(.el-dialog__header) {
    margin: 0;
    padding: 20px 30px;
    border-bottom: 1px solid #dcdfe6;
    
    .el-dialog__title {
      font-size: 16px;
      font-weight: 500;
      color: #333;
    }

    .el-dialog__close {
      font-size: 18px;
      margin-right: 10px;
    }
  }

  :deep(.el-dialog__body) {
    padding: 30px;
  }

  :deep(.el-dialog__footer) {
    padding: 20px 30px;
    border-top: 1px solid #dcdfe6;
  }

  :deep(.el-form-item) {
    margin-bottom: 25px;

    .el-form-item__label {
      font-weight: normal;
      &::before {
        margin-right: 4px;
        color: #ff4d4f;
      }
    }

    .el-input__wrapper {
      padding: 1px 11px;
    }
  }

  :deep(.material-code-item) {
    .el-input-group__append {
      padding: 0;
      .el-button {
        border: none;
        height: 32px;
        padding: 0 15px;
        border-radius: 0;
      }
    }
  }

  :deep(.version-item) {
    .el-input-number {
      width: 100%;
      .el-input__wrapper {
        padding-right: 0;
      }
      .el-input-number__decrease,
      .el-input-number__increase {
        background-color: #f5f7fa;
        border-color: #dcdfe6;
        &:hover {
          color: #409EFF;
        }
      }
    }
  }

  :deep(.el-radio-group) {
    .el-radio {
      margin-right: 30px;
      .el-radio__label {
        font-weight: normal;
      }
    }
  }

  :deep(.el-textarea__inner) {
    padding: 5px 11px;
    min-height: 100px;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;

  .el-button {
    min-width: 100px;
    padding: 9px 20px;
    margin: 0;
    
    &:last-child {
      margin-right: 8px;
    }
  }

  .cancel-button {
    border-color: #dcdfe6;
    &:hover {
      border-color: #c6e2ff;
      color: #409EFF;
      background-color: #ecf5ff;
    }
  }

  .confirm-button {
    min-width: 100px;
  }
}

.material-dialog {
  :deep(.el-dialog__header) {
    margin: 0;
    padding: 20px 30px;
    border-bottom: 1px solid #dcdfe6;
    
    .el-dialog__title {
      font-size: 16px;
      font-weight: 500;
      color: #333;
    }

    .el-dialog__close {
      font-size: 18px;
      margin-right: 10px;
    }
  }

  :deep(.el-dialog__body) {
    padding: 30px;
  }

  .search-header {
    margin-bottom: 20px;
    
    .search-inputs {
      display: flex;
      gap: 10px;
      align-items: center;

      .search-input {
        width: 200px;
      }

      .search-btn {
        background-color: #00925d;
        border-color: #00925d;
        padding: 8px 15px;
        
        &:hover {
          background-color: darken(#00925d, 10%);
          border-color: darken(#00925d, 10%);
        }
      }
    }
  }

  .material-pagination {
    margin-top: 20px;
    display: flex;
    justify-content: center;
    
    :deep(.el-pagination) {
      .el-pagination__total {
        color: #606266;
        font-weight: 400;
      }
      
      .btn-prev, .btn-next {
        background-color: #f4f4f5;
        color: #606266;
        border: 1px solid #dcdfe6;
      }
      
      .btn-prev:hover, .btn-next:hover {
        color: #409EFF;
      }
      
      .el-pager li {
        background-color: #f4f4f5;
        color: #606266;
        border: 1px solid #dcdfe6;
        margin: 0 2px;
      }
      
      .el-pager li:hover {
        color: #409EFF;
      }
      
      .el-pager li.is-active {
        background-color: #409EFF;
        color: #fff;
        border-color: #409EFF;
      }
    }
  }

  :deep(.el-table) {
    margin: 15px 0;
    
    .el-table__header-wrapper {
      th {
        background-color: #f5f7fa;
        color: #606266;
        font-weight: 500;
      }
    }
  }
}

.material-code-wrapper {
  display: flex;
  gap: 10px;
  align-items: center;
}

.material-input {
  flex: 1;
}

.search-button {
  padding: 8px 15px;
  background-color: #00925d;
  border-color: #00925d;

  &:hover {
    background-color: darken(#00925d, 10%);
    border-color: darken(#00925d, 10%);
  }
}

.bom-dialog {
  :deep(.el-dialog) {
    margin-top: 5vh !important;
  }
}

.material-dialog {
  :deep(.el-dialog) {
    margin-top: 8vh !important;
  }
}
</style>
